<template>
	<div>
		<el-card class="layout-search-card mb-4" shadow="never" :body-style="{ paddingBottom: '0' }">
			<el-form :model="storeState.queryParams" ref="queryForm" :inline="true" v-if="activeType == '1'">
				<el-form-item>
					<el-button size="default" type="primary" :icon="Refresh" circle @click="handleRefresh()" />
					<el-button v-if="!userInfo.is_login" v-auth="'addons/userLogin'" size="default" type="primary"  @click="handleLogin()"> 会员登录 </el-button>
					<el-button-group class="ml-[15px]" v-else>
						<el-button size="default" type="primary" :icon="Avatar"> {{ userInfo.account }} </el-button>
						<el-button v-auth="'addons/userLogout'" size="default" type="primary" :icon="SwitchButton" circle @click="handleLogout()" />
					</el-button-group>
				</el-form-item>
				<el-form-item label="应用名称：">
					<el-input v-model="storeState.queryParams.name" placeholder="请输入应用名称" class="w-180"> </el-input>
				</el-form-item>
				<el-form-item label="应用分类：">
					<el-select v-model="storeState.queryParams.category_id" placeholder="请选择应用分类" class="w-[180px]">
						<el-option v-for="item in categoryList" :key="item.value" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="searchStoreTable"> 查询 </el-button>
						<el-button icon="ele-Refresh" @click="resetStoreQuery" class="ml15 mr15"> 重置 </el-button>
						<el-button size="default" v-auth="'addons/import'" type="primary" @click="handleImport()" class="mr15"> 导入应用 </el-button>
					</el-button-group>
				</el-form-item>
			</el-form>
			<el-form :model="localState.queryParams" ref="queryForm" :inline="true" v-else>
				<el-form-item label="应用名称：">
					<el-input v-model="localState.queryParams.name" placeholder="请输入应用名称" class="w-180"> </el-input>
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="searchLocalTable"> 查询 </el-button>
						<el-button icon="ele-Refresh" @click="resetLocalQuery" class="ml15 mr15"> 重置 </el-button>
						<el-button size="default" v-auth="'addons/import'" type="primary" @click="handleImport()"> 导入应用 </el-button>
					</el-button-group>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card class="layout-table-card" shadow="never">
			<el-tabs v-model="activeType">
				<el-tab-pane label="全部应用" name="1">
					<el-row class="store-list" :gutter="5">
						<el-col v-for="(item, index) in storeState.tableList" :key="index" :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
							<div class="store-item" v-loading="storeState.loading" @click="handleDetail(item)">
								<div class="store-image">
									<img :src="item.thumb" :alt="item.name" />
								</div>
								<div class="store-info">
									<h3 class="store-title truncate">{{ item.name }}</h3>
									<p class="store-desc truncate">{{ item.describe }}</p>
									<div class="store-price">
										<span>
											<el-tag type="success" class="mr-[10px]">官方</el-tag>
											<el-tag type="primary">{{ item.category_name }}</el-tag>
										</span>
										<span v-if="item.local?.identify">
											<span v-if="compareVersions(item.version, item.local.version) > 0">
												<el-tag type="warning">待更新</el-tag>
											</span>
											<span v-else>
												<el-tag type="success">已安装</el-tag>
											</span>
										</span>
										<span v-else>
											<span v-if="item.is_buy"><el-tag type="success">已购买</el-tag></span>
											<span v-else>
												<span v-if="item.price">￥{{ item.price }}</span>
												<span v-else><el-tag>免费</el-tag></span>
											</span>
										</span>
									</div>
								</div>
							</div>
						</el-col>
					</el-row>
					<div class="flex justify-end mt-4">
						<pagination v-model="storeState" @tableChange="getStoreTableList" />
					</div>
				</el-tab-pane>
				<el-tab-pane label="本地应用" name="2">
					<el-table :data="localState.tableList" v-loading="localState.loading">
						<el-table-column prop="name" label="应用名称" show-overflow-tooltip></el-table-column>
						<el-table-column label="缩略图">
							<template #default="{ row }">
								<el-image
									class="h-[60px] flex items-center justify-center"
									:src="row.thumb"
									preview-teleported="true"
									:preview-src-list="[row.thumb]"
									fit="contain"
								/>
							</template>
						</el-table-column>
						<el-table-column prop="version" label="版本" show-overflow-tooltip></el-table-column>
						<el-table-column prop="status" label="类型" show-overflow-tooltip>
							<template #default="{ row }">
								<el-tag type="info" v-if="row.is_local">本地</el-tag>
								<el-tag type="success" v-else>商店</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="status" label="状态" show-overflow-tooltip>
							<template #default="{ row }">
								<el-tag type="success" v-if="row.status">{{ row.status_desc }}</el-tag>
								<el-tag type="danger" v-else>{{ row.status_desc }}</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="create_time" label="创建时间" show-overflow-tooltip></el-table-column>
						<el-table-column label="操作" width="100" fixed="right">
							<template #default="{ row }">
								<el-button v-if="row.is_local" v-auth="'addons/update'" size="small" text type="primary" @click="handleUpdate(row)">更新</el-button>
								<el-button v-else size="small" text type="primary" @click="handleDetail(row)">详情</el-button>
								<el-button v-auth="'addons/uninstall'" size="small" text type="primary" @click="handleUninstall(row)">卸载</el-button>
							</template>
						</el-table-column>
					</el-table>
					<div class="flex justify-end mt-4">
						<pagination v-model="localState" @tableChange="getLocalTableList" />
					</div>
				</el-tab-pane>
			</el-tabs>
		</el-card>
		<DetailDialog v-if="showDetailDialog" ref="detailDialogRef" @close="showDetailDialog = false" />
		<LoginDialog v-if="showLoginDialog" ref="loginDialogRef" @close="showLoginDialog = false" />
		<ImportDialog v-if="showImportDialog" ref="importDialogRef" @close="showImportDialog = false" />
		<UnInstallDialog v-if="showUnInstallDialog" ref="uninstallDialogRef" @close="showUnInstallDialog = false" />
	</div>
</template>

<script setup lang="ts" name="appStoreList">
import { reactive, ref, onMounted, nextTick } from 'vue';
import { manageUserInfo, manageLogout, manageRefresh, manageList, manageLocalLists, manageCategoryLists } from '/@/api/addons/manage';
import { usePage } from '/@/hooks/usePage';
import { messageBox, messageSuccess } from '/@/utils/message';
import { compareVersions } from '/@/utils/util';
import { Refresh, Avatar, SwitchButton } from '@element-plus/icons-vue'
import DetailDialog from '/@/views/appStore/component/detail.vue';
import LoginDialog from '/@/views/appStore/component/login.vue';
import ImportDialog from '/@/views/appStore/component/import.vue';
import UnInstallDialog from '/@/views/appStore/component/uninstall.vue';

const detailDialogRef = ref();

const showDetailDialog = ref(false);

const loginDialogRef = ref();

const showLoginDialog = ref(false);

const importDialogRef = ref();

const showImportDialog = ref(false);

const uninstallDialogRef = ref();

const showUnInstallDialog = ref(false);

const activeType = ref('1');

// 商店应用
const storeState = reactive<TableDataState>({
	loading: false,
	tableList: [],
	queryParams: {
		name: '',
		category_id: '',
	},
	tableParams: {
		page_num: 1,
		page_limit: 15,
		page_total: 0 as any,
	},
});

// 本地应用
const localState = reactive<TableDataState>({
	loading: false,
	tableList: [],
	queryParams: {
		title: '',
		status: '',
		cate_id: '',
	},
	tableParams: {
		page_num: 1,
		page_limit: 15,
		page_total: 0 as any,
	},
});

const { 
	getTableList: getStoreTableList, 
	searchTable: searchStoreTable, 
	resetQuery: resetStoreQuery 
} = usePage({ tableData: storeState, apiData: manageList });

const { 
	getTableList: getLocalTableList, 
	searchTable: searchLocalTable, 
	resetQuery: resetLocalQuery 
} = usePage({ tableData: localState, apiData: manageLocalLists });

const categoryList = ref<Array<any>>([]);

// 应用分类
const getCategoryList = async () => {
	const data = await manageCategoryLists();
	categoryList.value = data;
};

const userInfo = reactive({
	account: "",
	is_login: 0
});

// 应用分类
const getUserInfo = async () => {
	const data = await manageUserInfo();
	userInfo.account = data.account;
	userInfo.is_login = data.is_login;
};

// 详情
const handleDetail = async (row: any) => {
    showDetailDialog.value = true;
    nextTick(() => {
        detailDialogRef.value?.setFormData(row, () => {
            detailDialogRef.value?.open();
        });
    });
};

// 卸载
const handleUninstall = async (row: any) => {
	messageBox('确认要卸载应用吗？卸载后数据不可恢复').then(async () => {
        showUnInstallDialog.value = true;
        nextTick(() => {
            uninstallDialogRef.value?.setFormData(row, () => {
                uninstallDialogRef.value?.open();
            });
        });
	});
};

// 更新
const handleUpdate = async (row: any) => {
	showImportDialog.value = true;
    nextTick(() => {
		importDialogRef.value?.setFormData(row, () => {
			importDialogRef.value?.open('update');
		});
    });
};

// 导入
const handleImport = async () => {
    showImportDialog.value = true;
    nextTick(() => {
		importDialogRef.value?.open('add');
    });
};

// 登录
const handleLogin = async () => {
    showLoginDialog.value = true;
    nextTick(() => {
		loginDialogRef.value?.open();
    });
};

//退出
const handleLogout = async () => {
	messageBox('确认要会员退出登录吗？').then(async () => {
		await manageLogout();
		messageSuccess('退出登录成功',()=>{
			getUserInfo();
		});
	});
}

// 刷新缓存
const handleRefresh = async () => {
	await manageRefresh();
	messageSuccess('刷新缓存成功');
};

onMounted(() => {
	getStoreTableList();
	getLocalTableList();
	getCategoryList();
	getUserInfo();
});
</script>
<style lang="scss">
.store-list {
	margin-bottom: 40px;
	margin-top: 15px;
}

.store-item {
	margin: 5px;
	overflow: hidden;
	cursor: pointer;
    box-shadow: var(--el-box-shadow-light);
	border-radius: var(--el-border-radius-base);
	transition: transform 0.3s ease;

	&:hover {
		transform: translateY(-5px);
		border: 1px solid var(--el-color-primary);
	}

	.store-image {
		width: 100%;
		height: 160px;
		overflow: hidden;

		img {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}
	}

	.store-info {
		padding: 15px;

		.store-title {
			font-size: 18px;
			margin-bottom: 10px;
			color: var(--el-color-primary);
		}

		.store-desc {
			font-size: 14px;
			color: #666;
			line-height: 1.5;
			margin-bottom: 15px;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		.store-price {
			display: flex;
			font-size: 16px;
			color: var(--el-color-danger);
			justify-content: space-between;
		}
	}
}
</style>
